package com.sh.data.engine.domain.normalization.modeldesign.model.service;

import com.sh.data.engine.domain.normalization.modeldesign.model.model.domain.CreateTableDomain;
import com.sh.data.engine.domain.normalization.modeldesign.model.model.domain.ModelDomain;
import com.sh.data.engine.domain.normalization.modeldesign.model.model.param.SaveModelParam;
import com.sh.data.engine.domain.normalization.modeldesign.model.service.impl.ModelServiceImpl;
import com.sh.data.engine.domain.shims.db.BaseDbManager;
import com.sh.data.engine.domain.shims.db.model.TableInfoDomain;
import com.sh.data.engine.domain.shims.sql.builder.DDLBuilder;

import java.sql.SQLException;
import java.util.List;

/**
 * table operation interface 表操作策略接口, 具体表操作需要实现该接口
 */
public interface TableOperationStrategy {
    List<ModelDomain.Field> getTableField(
        String dbName, String schema, String tableName, BaseDbManager dbManager);

    boolean createTable(CreateTableDomain createTableDomain);

    boolean editFormTable(
        String dbName,
        String schema,
        ModelDomain dbModel,
        SaveModelParam saveModelParam,
        BaseDbManager dbManager);

    boolean isTableNameExist(String dbName, String schema, String tableName, BaseDbManager dbManager);

    TableInfoDomain getTableInfoDomain(
        String dbName, String schema, String tableName, BaseDbManager dbManager);

    /**
     * 解析字段变更
     *
     * @param dbModel
     * @param saveModelParam
     * @return
     */
    ModelServiceImpl.FieldsParseResult parseFields(
        ModelDomain dbModel, SaveModelParam saveModelParam);

    /**
     * @param dbName
     * @param schemaName
     * @param tableName
     * @param dbManager
     * @return
     */
    default boolean dropTable(
        String dbName, String schemaName, String tableName, BaseDbManager dbManager) {
        try {
            DDLBuilder ddlBuilder = dbManager.getDDLBuilder();
            ddlBuilder.dropTable(schemaName, tableName).execute();
            return true;
        } catch (SQLException e) {
            return false;
        }
    }

    default void closeDbManager(BaseDbManager dbManager) {
        if (null != dbManager) {
            dbManager.close();
        }
    }
}
